import { defineStore } from 'pinia';

export const useExamListStore = defineStore('examList', () => {
  const examList = ref<any[]>([]);
  function formatDate(dateStr: string): string {
    if (dateStr.length !== 4) {
      throw new Error('Invalid date format');
    }
    const month = dateStr.substring(0, 2);
    const day = dateStr.substring(2, 4);
    const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
    const monthName = monthNames[Number.parseInt(month, 10) - 1];
    return `${monthName}${day}日`;
  }
  function getUniqueExamLevelsWithDates(exams: any[]): { [key: string]: string[] } {
    return exams.reduce((acc, exam) => {
      if (!acc[exam.examLevel]) {
        acc[exam.examLevel] = [];
      }
      acc[exam.examLevel].push({
        date: formatDate(exam.examDate.substring(0, 4)),
        event: exam.examEvent,
      });
      return acc;
    }, {} as { [key: string]: string[] });
  }
  function convertToObjectArray(data: { [key: string]: string[] }): any[] {
    return Object.keys(data).map(key => ({
      examName: key,
      examDates: data[key],
    }));
  }
  const getExamList = async () => {
    let data: any[] = [];
    await getAllExam().then((res: any) => {
      data = res.data;
    });
    const exam = getUniqueExamLevelsWithDates(data);
    examList.value = convertToObjectArray(exam);
  };
  const getExam = () => {
    const data = [];
    for (let i = 0; i < examList.value.length; i++) {
      data.push(examList.value[i].examLevel);
    }
    return data;
  };
  const getDateByExam = (exam: string) => {
    for (let i = 0; i < examList.value.length; i++) {
      if (examList.value[i].examLevel === exam) {
        return examList.value[i].examDates;
      }
    }
  };
  return {
    examList,
    getExamList,
    getDateByExam,
    getExam,
  };
}, {
  persist: true,
});
